// pages/Nexu/Nexu.js
const img = require('../../_self/msets.js').default_share_bg;
const db = wx.cloud.database();
var sev = require('../../utils/sev.js');
const app = getApp();
const _ = db.command;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    img:'',
    nexulist:[],
    modalName:null,
    searchKey:'',
    favor:false,
    nexuid:'',
    favorid:'',//喜欢的id
    cloud:true,
    jindu: 0,//下载进度
    
  },
  pub(){
    //
    wx.navigateTo({
      url: 'Pub/Pub',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({img})
    that.ReqList();
  },
  getkey(e) {
    this.setData({
      searchKey: e.detail.value
    })
  },
  match(){
    var that = this;
    that.setData({
      nexulist:[]
    },()=>{
      that.ReqList();
    })
  },
  ReqList(){
    var that  = this;
    var len = that.data.nexulist.length;
    if(that.data.searchKey!=''){
      db.collection('NEXUSET').skip(len).where(_.or([{
        sofname: db.RegExp({
          regexp: that.data.searchKey,
          options: 'm',
        })
      },
      {
        fileurls: db.RegExp({
          regexp: that.data.searchKey,
          options: 'm',
        })
      }])).orderBy('dbdate','desc').get().then(res=>{
        console.log(res)
        that.setData({
          nexulist:that.data.nexulist.concat(res.data)
        })
      })
    }else{
      db.collection('NEXUSET').skip(len).orderBy('dbdate','desc').get().then(res=>{
        console.log(res)
        that.setData({
          nexulist:that.data.nexulist.concat(res.data)
        })
      })
    }
    
  },
  showModal(e) {
    //console.log(e)
    var filelist = e.currentTarget.dataset.info.fileurls;
    var docid = e.currentTarget.dataset.info._id;
    var fvname = e.currentTarget.dataset.info.sofname;
    var cloud = e.currentTarget.dataset.info.source == 'cloud'?true:false;
    wx.showLoading();
    db.collection('FAVOR').where({
      uid:app.globalData.openid,
      nexuid:docid
    }).get().then(res=>{
      console.log(res)
      wx.hideLoading();
      if(res.data.length == 0){
        this.setData({
          modalName: 'sdetail',
          nexuid:docid,
          fvname,
          filelist,
          favor:false,
          cloud,
          jindu:0
        })
      }else{
        this.setData({
          modalName: 'sdetail',
          nexuid:docid,
          favor:true,
          fvname,
          favorid:res.data[0]._id,
          filelist,
          cloud,
          jindu:0
        })
      }
    })
    //console.log(docid)
   
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
   clv(){
    wx.getSavedFileList({  // 获取文件列表
      success (res) {
        res.fileList.forEach((val, key) => { // 遍历文件列表里的数据
            // 删除存储的垃圾数据
          wx.removeSavedFile({
              filePath: val.filePath
          });
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  downFile(e){
    //console.log(e)
   this.clv();
    var fdetail = e.currentTarget.dataset.detail;
   var iscloud = this.data.cloud;
   var downloadTask = null;
    if(iscloud){
       downloadTask = wx.cloud.downloadFile({
        fileID: fdetail.fileurl,
        success(res) {
          var finfo = wx.getFileInfo({
            filePath: res.tempFilePath,
            success:f=>{
              if(f.size > 8888888 ){
                wx.showModal({
                  title: '是否打开文件',
                  content: '',
                  success(ans) {
                    if (ans.confirm) {
                      wx.openDocument({
                        filePath: res.tempFilePath,
                      })
                    }
                  }
                })
              }else{
                wx.getFileSystemManager().saveFile({
                  tempFilePath: res.tempFilePath,
                   filePath: wx.env.USER_DATA_PATH + "/" + fdetail.filename,
                })
                wx.showModal({
                  title: '是否打开文件',
                  content: '',
                  success(ans) {
                    if (ans.confirm) {
                      wx.openDocument({
                        filePath: wx.env.USER_DATA_PATH + "/" + fdetail.filename,
                      })
                    }
                  }
                })
              }
            }
          })
          
        }
      })
      downloadTask.onProgressUpdate((res) => {
        this.setData({
          jindu: res.progress
        })
      })
    }
    else{
      //转储方式
      wx.showLoading({
        title: '转储~',
      })
      wx.cloud.callFunction({
        name:'transfile',
        data:{
          url:fdetail.fileurl,
          type:'dump',
          filename:fdetail.filename
        },
        success:f=>{
          //console.log(f)
          wx.hideLoading();
           downloadTask =wx.cloud.downloadFile({
            fileID: f.result.fileID,
            success(res) {
              var finfo = wx.getFileInfo({
                filePath: res.tempFilePath,
                success:f=>{
                  if(f.size > 8888888 ){
                    wx.showModal({
                      title: '是否打开文件',
                      content: '',
                      success(ans) {
                        if (ans.confirm) {
                          wx.openDocument({
                            filePath: res.tempFilePath,
                          })
                        }
                      }
                    })
                  }else{
                    wx.getFileSystemManager().saveFile({
                      tempFilePath: res.tempFilePath,
                       filePath: wx.env.USER_DATA_PATH + "/" + fdetail.filename,
                    })
                    wx.showModal({
                      title: '是否打开文件',
                      content: '',
                      success(ans) {
                        if (ans.confirm) {
                          wx.openDocument({
                            filePath: wx.env.USER_DATA_PATH + "/" + fdetail.filename,
                          })
                        }
                      }
                    })
                  }
                }
              })
              
            }
          })
          downloadTask.onProgressUpdate((res) => {
            this.setData({
              jindu: res.progress
            })
          })
        },
        fail:f=>{
          console.log(f)
        }
      })
    }
    
  },
  favor(){
    var that = this;
    var fv = that.data.favor;
    if(fv){
      db.collection('FAVOR').doc(that.data.favorid).remove().then(res=>{
        console.log(res)
        that.setData({
          favor:false
        })
      })
    }else{
      wx.cloud.callFunction({
        name:'kindb',
        data:{
          opr:'add',
          tablename:'FAVOR',
          data:{
            uid:app.globalData.openid,
            nexuid:that.data.nexuid,
            fvname:that.data.fvname
          }
        },
        success:res=>{
          that.setData({
            favor:true
          })
        }
      })
    }
  },
    
  
  onReady: function () {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    that.setData({
      nexulist:[]
    },()=>{
      wx.stopPullDownRefresh({
        complete: (res) => {},
      })
      that.ReqList();
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    that.ReqList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})